package com.bwie.ai;

import com.bwie.common.security.annotation.EnableRyFeignClients;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;

@SpringBootApplication
@EnableRyFeignClients
public class AiApplication {
    public static void main(String[] args) {
        SpringApplication.run(AiApplication.class);
    }

    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }

    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        return new SimpleVectorStore(embeddingModel);
    }

    /**
     * 写入向量数据库
     * @param embeddingModel
     * @param vectorStore
     * @param termsOfService
     * @return
     */
    @Bean
    public CommandLineRunner ingestTermOfServiceToVectorStore(EmbeddingModel embeddingModel, VectorStore vectorStore, @Value("classpath:www.txt") Resource termsOfService){
        return args -> {
            vectorStore.write( //3.写入
                    new TokenTextSplitter().transform( //2.转换
                            new TextReader(termsOfService).read())//1.读取
            );
        };
    }
}
